package com.yuanian.ecsplus.threadlocal;

import org.springframework.core.NamedThreadLocal;

import java.util.HashMap;
import java.util.Map;

public class ThreadLocalMap {

    private static ThreadLocal<Map<Object, Object>> map = new NamedThreadLocal("ThreadLocalMap") {
        @Override
        protected Map<Object, Object> initialValue() {
            return new HashMap<>();
        }
    };

    public static void put(Object key, Object obj) {
        map.get().put(key, obj);
    }

    public static <T> T get(Object key, Class<T> clz) {
        Object obj = map.get().get(key);
        if (obj != null && obj.getClass() == clz) {
            return (T) obj;
        }
        return null;
    }

    public static <T> T get(Object key) {
        Object obj = map.get().get(key);
        return obj != null ? (T) obj : null;
    }

    public static void clear() {
        map.remove();
    }

    public static void main(String[] args) {
        ThreadLocalMap.put("x" , 1);
        ThreadLocalMap.put("y" , "xxx");
        Integer a = ThreadLocalMap.get("x");
        System.out.println(a);

        String b = ThreadLocalMap.get("y", String.class);
        System.out.println(b);


        new Thread(new Runnable() {
            @Override
            public void run() {
                String b = ThreadLocalMap.get("y", String.class);
                System.out.println("thread : " + b);
            }
        }).start();


        String b1 = ThreadLocalMap.get("y", String.class);
        System.out.println(b1);
    }
}

